package com.hippo.core.vm

import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.hippo.core.event.MessageEvent
import com.hippo.core.event.MessageEventBus
import com.hippo.core.ui.compose.main.MainState
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode

class MainVM : ViewModel() {

    private val _eventChannel = Channel<MessageEvent>(Channel.BUFFERED)
    val eventFlow = _eventChannel.receiveAsFlow()

    var uiState by mutableStateOf(MainState())

    init {
        MessageEventBus.register(this)
    }


    fun updateState(state: MainState) {
        uiState = state
    }



    override fun onCleared() {
        super.onCleared()
        MessageEventBus.unregister(this)
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: MessageEvent) {
        Log.i("sss", "onMessageEvent: $event")
        viewModelScope.launch {
            _eventChannel.send(event)
        }
    }

}